<?php

namespace app\common\helper;

use app\common\model\AiImage;
use app\common\model\AiOrder;
use GuzzleHttp\Client;
use think\helper\Str;

class WanX
{
    protected $uris;
    protected $api_key;
    protected $url;
    protected $model;
    protected $path;
    public function __construct()
    {
        $this->api_key = cache('config')['wan_api_key'];
        $this->path = "uploads/xcx/" . date("Ym");
        $this->uris = [
            'v1' => [
                'url' => 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis',
                'model' => 'wanx-v1'
            ],
            'back' => [
                'url' => 'https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/',
                'model' => 'wanx-background-generation-v2'
            ],
            'repaint' => [
                'url' => 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation',
                'model' => 'wanx-style-repaint-v1'
            ],
        ];
    }
    // 背景生成
    public function back($order)
    {
        $this->url = $this->uris['back']['url'];
        $this->model = $this->uris['back']['model'];
        $data = [
            'model' => $this->model,
            "input" => [
                "base_image_url" => request()->domain() . $order->base_image_url,
                "ref_image_url" => $order->ref_image_url ? request()->domain() . $order->ref_image_url : '',
                "ref_prompt" => $order->ref_prompt,
                "title" => $order->title,
                "sub_title" => $order->sub_title,
                "reference_edge" => [
                    "foreground_edge" => $order->foreground_edge ? [request()->domain() . $order->foreground_edge] : '',
                    "background_edge" => $order->background_edge ? [request()->domain() . $order->background_edge] : '',
                ],
                "parameters" => [
                    "n" => $order->n,
                    "scene_type" => $order->scene_type,
                ]
            ],
        ];
        return $this->send($data);
    }
    // 人像重绘
    public function repaint($order)
    {
        $this->url = $this->uris['repaint']['url'];
        $this->model = $this->uris['repaint']['model'];
        $data = [
            'model' => $this->model,
            "input" => [
                "image_url" => request()->domain() . $order->image_url,
                "style_index" => $order->style_index,
            ],
        ];
        return $this->send($data);
    }

    // 文生图
    public function search($task_id)
    {
        $result = $this->getTask($task_id);
        if (isset($result['output']['task_status'])) {
            $order = AiOrder::where('task_id', $result['output']['task_id'])->find();
            $order->task_status = $result['output']['task_status'];
            if ($result['output']['task_status'] == 'SUCCEEDED') {
                if ($order) {
                    if (!is_dir(public_path() . $this->path))
                        mkdir(public_path() . $this->path, 0755, true);
                    $this->v1TaskBack($order,$result,$this->path);
                }
            } elseif (in_array($result['output']['task_status'], ['PENDING', 'RUNNING'])) {
                queue('app\common\job\AiOrder@pull',$order->id,7,'pull');
            }
        }
        return $result;
    }

    public function send($data)
    {
        $client = new Client();
        $result = $client->post($this->url, [
            "headers" => [
                "Content-Type" => 'application/json',
                "Authorization" => 'Bearer ' . $this->api_key,
                "X-DashScope-Async" => 'enable'
            ],
            'json' => $data
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }

    public function v1($content, $n = 1, $size = '720*1280')
    {
        $this->url = $this->uris['v1']['url'];
        $this->model = $this->uris['v1']['model'];
        $data = [
            'model' => $this->model,
            "input" => [
                "prompt" => $content,
                "negative_prompt" => '丑陋、重复、病态、残缺、超出框架、多余的手指、变异的手、画得不好的手、画得不好的脸、突变、变形、模糊、脱水、不良的解剖结构、 比例不良、多余肢体、克隆脸、毁容、总体比例、畸形肢体、缺臂、缺腿、多余手臂、多余腿、融合手指、手指过多、长脖子'
            ],
            "parameters" => [
                "n" => $n,
                "size" => $size, //目前仅支持'1024*1024', '720*1280', '1280*720'三种分辨率，默认为1024*1024像素
            ]
        ];
        return $this->send($data);
    }

    public function getTask($task_id)
    {
        $client = new Client();
        $url = "https://dashscope.aliyuncs.com/api/v1/tasks/{$task_id}";
        $result = $client->get($url, [
            "headers" => [
                "Content-Type" => 'application/json',
                "Authorization" => 'Bearer ' . $this->api_key,
                "X-DashScope-Async" => 'enable'
            ]
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }

    public function v1TaskBack($order,$result,$path)
    {
        $order->success_time = $result['output']['end_time'];
        $order->save();
        $image = $result['output']['results'];
        foreach ($image as $item) {
            if ($item['url']) {
                $oss = new AliOss();
                $name = $path . "/" . md5(time() . Str::random()) . ".png";
                $files = AiImage::create([
                    "path" => "/". $name,
                    "type" => $order->type,
                    "user_id" => $order->user_id,
                    "prompt" => $order->prompt,
                    "order_id" => $order->id,
                    "create_time" => time(),
                    "origin_url" => $item['url']
                ]);
                $file = @file_get_contents($item['url']);
                @file_put_contents( public_path() . $name, $file);
                if ($order->type == 'v1') { // 传阿里云
//                    $oss->multiUploadFile($name,  public_path() . $name, $files->id);
                }
            }
        }
    }


    // 千问
    public function qianwen($content,$model='qwen-turbo')
    {
        $client = new Client();
        $url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        $result = $client->post($url, [
            "headers" => [
                "Content-Type" => 'application/json',
                "Authorization" => 'Bearer ' . $this->api_key,
            ],
            'json' => [
                "model" => $model,
                "input" => [
                    "prompt" => $content,
                ]
            ]
        ]);
        return json_decode($result->getBody()->getContents(), true);
    }
}